package com.aniu.cameramanager;

import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import com.aniu.cameramanager.util.CameraUtil;
import com.aniu.cameramanager.util.WorkTime;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = MainActivity.class.getSimpleName();

    private DevicePolicyManager devicePolicyManager;
    private ComponentName deviceAdmin;

    protected static final int REQUEST_ENABLE = 1;

    private Button mBtnActivate, mBtnSetting, mBtnSetAutoStart;
    private TextView mTvMain;

    private int amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "------------------onCreate------------------");
        setContentView(R.layout.activity_main);

        refreshWorkTime();

        mBtnActivate = findViewById(R.id.activate);
        mBtnActivate.setOnClickListener(this);
        mBtnSetting = findViewById(R.id.set_work_time);
        mBtnSetting.setOnClickListener(this);
        mBtnSetAutoStart = findViewById(R.id.set_auto_start);
        mBtnSetAutoStart.setOnClickListener(this);


        devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        deviceAdmin = new ComponentName(this, MyDeviceAdminReceiver.class);

        if (!(devicePolicyManager.isAdminActive(deviceAdmin))) {
            startActivateDeviceAdminActivityForResult();

        } else {
            Log.i(TAG, "已经有admin权限，无需处理");
            disableBtnActivate();
            CameraUtil.blockOrUnblockCameraNow(this, amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime);
        }

        alertToSetAutoStart();
    }

    private void refreshBtnActivate() {
        if (devicePolicyManager.isAdminActive(deviceAdmin)) {
            disableBtnActivate();
        } else {
            mBtnActivate.setText(getString(R.string.activate));
            mBtnActivate.setEnabled(true);
        }
    }

    private void disableBtnActivate() {
        mBtnActivate.setText("已激活设备管理器");
        mBtnActivate.setEnabled(false);
    }

    private void startActivateDeviceAdminActivityForResult() {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(
                DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                deviceAdmin);
        intent.putExtra(
                DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                getString(R.string.admin_explanation));
        startActivityForResult(intent, REQUEST_ENABLE);
    }

    /**
     * 提示用户设置自启动和后台运行
     */
    private void alertToSetAutoStart() {
        final SharedPreferences.Editor pref = getSharedPreferences("allow_notify", MODE_PRIVATE).edit();
        pref.apply();
        final SharedPreferences sp = getSharedPreferences("allow_notify", MODE_PRIVATE);

        // 只弹一次
        if(!sp.getBoolean("protected",false)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder
                    .setTitle(getString(R.string.auto_start_alert_title))
                    .setMessage(getString(R.string.auto_start_alert_content))
                    .setPositiveButton(getString(R.string.auto_start_alert_ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            startAutoStartActivity();
                        }
                    })
                    .setCancelable(false)
                    .setNegativeButton(getString(R.string.auto_start_alert_cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .create().show();
            sp.edit().putBoolean("protected", true).apply();
        }
    }

    private void startAutoStartActivity() {
        final Intent[] POWERMANAGER_INTENTS = {
                new Intent().setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
                new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
                new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
                new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
                new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
                new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
                new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
                new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
                new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
                new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
                new Intent().setComponent(new ComponentName("com.samsung.android.lool", "com.samsung.android.sm.ui.battery.BatteryActivity")),
                new Intent().setComponent(new ComponentName("com.htc.pitroad", "com.htc.pitroad.landingpage.activity.LandingPageActivity")),
                new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.MainActivity")),
                new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.privacypermissionsentry.PermissionTopActivity"))};

        // 是否匹配到Intent
        boolean matchSuccess = false;
        for (final Intent intent : POWERMANAGER_INTENTS) {
            if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                try {
                    startActivity(intent);
                    matchSuccess = true;
                    break;
                } catch (Exception e) {
                    Log.e(TAG, "启动 " + intent.getComponent().getClassName() + " 报错，错误信息: "
                            + e.getMessage());
                }
            }
        }

        if (!matchSuccess) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder
                    .setTitle(getString(R.string.auto_start_alert_title))
                    .setMessage(getString(R.string.auto_start_fail))
                    .setPositiveButton(getString(R.string.auto_start_fail_ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .create().show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "------------------onStart------------------");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "------------------onResume------------------");
        refreshWorkTime();
        refreshBtnActivate();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "------------------onRestart------------------");
    }

    /**
     * 获取设置的工作时间并刷新页面
     */
    private void refreshWorkTime() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        amStartWorkTime = sharedPreferences.getInt(WorkTime.AM_START_WORK_KEY, WorkTime.AM_START_WORK_DEFAULT_TIME);
        amStopWorkTime = sharedPreferences.getInt(WorkTime.AM_STOP_WORK_KEY, WorkTime.AM_STOP_WORK_DEFAULT_TIME);
        pmStartWorkTime = sharedPreferences.getInt(WorkTime.PM_START_WORK_KEY, WorkTime.PM_START_WORK_DEFAULT_TIME);
        pmStopWorkTime = sharedPreferences.getInt(WorkTime.PM_STOP_WORK_KEY, WorkTime.PM_STOP_WORK_DEFAULT_TIME);

        mTvMain = findViewById(R.id.tv_main_content);
        String content = getResources().getString(R.string.hello_world);
        String newContent = String.format(content, WorkTime.timeInt2String(amStartWorkTime), WorkTime.timeInt2String(amStopWorkTime),
                WorkTime.timeInt2String(pmStartWorkTime), WorkTime.timeInt2String(pmStopWorkTime));
        mTvMain.setText(newContent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_ENABLE:
                    Log.i(TAG, "没有admin权限，获取成功");
                    disableBtnActivate();
                    CameraUtil.blockOrUnblockCameraNow(this, amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime);
                    break;
            }
        } else {
            Log.i(TAG, "没有admin权限，获取失败，错误码：" + resultCode);
//            Intent intent = new Intent(this, CameraListenerService.class);
//            startService(intent);
//            Log.i(TAG, "相机监听服务已启动");
        }
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();

        switch (viewId) {
            case R.id.set_work_time :
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                break;

            case R.id.activate :
                startActivateDeviceAdminActivityForResult();
                break;

            case R.id.set_auto_start :
                startAutoStartActivity();
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "------------------onStop------------------");
    }
}